package com.example.util;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * Created by simon on 2017/10/3
 */
public class JpushUtil {
    /**
     * 日志记录器
     */
    private static Logger logger = Logger.getLogger(JpushUtil.class);

    private JPushClient jpushClient;

    private String title;

    private String message;

    @SuppressWarnings("deprecation")
    public JpushUtil(String appKey, String masterSecret, String message, String title) {

        jpushClient = new JPushClient(masterSecret, appKey, 3); //重试三次
        this.message = message;
        this.title = title;
    }

    /**
     * 按照deviceId发送，不区分Andorid和IOS, 若deviceIds为空则发送所有人
     *
     * @return
     */
    public boolean sendPushAll(boolean isProductEnv, List<String> deviceIds) {
        PushPayload payload = buildPushObject_all_all_alert(isProductEnv, deviceIds);
        boolean isSuccess = true;
        try {
            // PushResult result = jpushClient.sendNotificationAll(message);//
            // sendPush(payload);
            PushResult result = jpushClient.sendPush(payload);
            isSuccess = result.isResultOK();
        } catch (APIConnectionException e) {
            isSuccess = false;
            logger.info("Connection error. Should retry later. ");
        } catch (APIRequestException e) {
            isSuccess = false;
            logger.info("HTTP Status: " + e.getStatus());
        }
        return isSuccess;
    }

    /**
     * 发全安卓设备  通知
     * @param msgType
     * @return
     */
    public boolean sendPushAndroidAll(String msgType) {
        boolean isSuccess = true;
        PushPayload payload = buildPushNotify_Android_all_alert();
        try {
            PushResult result = jpushClient.sendPush(payload);
            isSuccess = result.isResultOK();
        } catch (APIConnectionException e) {
            isSuccess = false;
            logger.info("sendPushAndroidAll failed");
        } catch (APIRequestException e) {
            isSuccess = false;
            System.out.println("HTTP Status: " + e.getStatus());
            logger.error("sendPushAndroidAll failed", e);
        }
        return isSuccess;
    }

    /**
     * android根据设别号发送
     *
     * @param deviceIds
     * @return
     */
    public boolean sendPushAndroidDevices(String... deviceIds) {
        boolean isSuccess = true;
        PushResult result = null;
        try {
            result = jpushClient.sendAndroidNotificationWithRegistrationID(title, message, null, deviceIds);
            isSuccess = result.isResultOK();
        } catch (APIConnectionException e) {
            isSuccess = false;
            logger.error("sendPushAndroidAlias error", e);
        } catch (APIRequestException e) {
            isSuccess = false;
            e.printStackTrace();
            logger.error("sendPushAndroidAlias error", e);
        }

        return isSuccess;
    }

    /**
     * ios根据设备号发送
     *
     * @return
     */
    public boolean sendPushIosDevices(boolean isProductEnv, String[] deviceIds) {
        boolean isSuccess = true;
        PushResult result = null;
        PushPayload payload = buildPushObject_ios_regist_alert(isProductEnv, deviceIds);
        try {
            result = jpushClient.sendPush(payload);
            isSuccess = result.isResultOK();
        } catch (APIConnectionException e) {
            isSuccess = false;
            logger.error("sendPushIosAlias error", e);
        } catch (APIRequestException e) {
            isSuccess = false;
            logger.error("sendPushIosAlias error", e);
        }

        return isSuccess;
    }

    /**
     * 发送给所有ios设备
     * @param isProductEnv
     * @return
     */
    public boolean sendPushIosAll(boolean isProductEnv) {
        boolean isSuccess = true;
        PushPayload payload = buildPushObject_ios_all_alert(isProductEnv);
        try {
            PushResult result = jpushClient.sendPush(payload);
            isSuccess = result.isResultOK();
        } catch (APIConnectionException e) {
            isSuccess = false;
            logger.error("sendPushIosAll failed", e);
        } catch (APIRequestException e) {
            isSuccess = false;
            logger.error("sendPushIosAll failed", e);
        }
        return isSuccess;
    }

    /**
     * 构建 全机型 指定设备号 或取全设备 的 PushPayload
     * @param isProductEnv
     * @param deviceIds
     * @return
     */
    public PushPayload buildPushObject_all_all_alert(boolean isProductEnv, List<String> deviceIds) {
        if (deviceIds == null || deviceIds.size() == 0) {
            return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.all())
                    .setNotification(Notification.alert(message))
                    .setOptions(Options.newBuilder().setApnsProduction(isProductEnv).build()).build();
        } else {
            return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.registrationId(deviceIds))
                    .setNotification(Notification.alert(message))
                    .setOptions(Options.newBuilder().setApnsProduction(isProductEnv).build()).build();
        }
    }

    /**
     * 构建 ios全设备 PushPayload
     * @param isProductEnv
     * @return
     */
    public PushPayload buildPushObject_ios_all_alert(boolean isProductEnv) {
        return PushPayload.newBuilder().setPlatform(Platform.ios()).setAudience(Audience.all())
                .setNotification(Notification.alert(message))
                .setOptions(Options.newBuilder().setApnsProduction(isProductEnv).build()).build();
    }

    /**
     * 构建 安卓全设备 PushPayload
     * @return
     */
    public PushPayload buildPushNotify_Android_all_alert() {
        return PushPayload.newBuilder().setPlatform(Platform.android()).setAudience(Audience.all())
                .setNotification(Notification.android(message, title, null))
                .setOptions(Options.newBuilder().setApnsProduction(true).build()).build();
    }

    /**
     * 构建 ios 设备号 PushPayload
     * @param isProductEnv
     * @param devices
     * @return
     */
    public PushPayload buildPushObject_ios_regist_alert(boolean isProductEnv, String[] devices) {
//        Map<String,String> map = new HashMap<String,String>();
//        map.put("title", title);
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.registrationId(devices))
                .setNotification(Notification.alert(message))
                .setOptions(Options.newBuilder().setApnsProduction(isProductEnv).build()).build();
    }


    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

